package com.cloud.point.designPattern.observer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * ObserverManager
 *
 * @author H
 * @version 1.0
 * @date 2024-03-28 15:45
 */
@Service
public class ObserverManager implements InitializingBean {

    @Resource
    private ApplicationContext applicationContext;
    private final List<TransferObserver> observerList = new ArrayList<>();

    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, TransferObserver> observerMap = applicationContext.getBeansOfType(TransferObserver.class);
        observerMap.values().forEach(this::addObserver);
    }

    /**
     * 触发观察者
     *
     * @param transferEvent
     */
    public void notifyObservers(TransferEvent transferEvent) {
        observerList.forEach(t -> {
            executorService.execute(() -> {
                t.updateInfo(transferEvent);
            });
        });
    }

    /**
     * 添加观察者
     *
     * @param observer
     */
    private void addObserver(TransferObserver observer) {
        observerList.add(observer);
    }

}
